<?php

/**
 * Base-class untuk semua jenis grader 
 */
abstract class GraderBase {

    protected $compiler;
    protected $requestModel;
    protected $gradeResult;

    public function __construct($pCompiler) {
        $this->compiler = $pCompiler;
        $this->requestModel = $pCompiler->getRequestModel();
    }

    protected abstract function beforeGrade();

    protected function afterGrade() {
       	$this->compiler->cleanup();
        $this->requestModel->grader_id = $_SERVER['SERVER_ADDR'];
        $this->requestModel->save();
    }

    protected abstract function doGrade();

    protected function execute($command, &$output) {
        $out = array();
        $retval = 0;
        exec($command, $out, $retval);

        $output = implode("\n", $out);
        return $retval;
    }

    public final function grade() {
        if ($this->compiler->getCompileReturnValue() == 0) {
            $this->beforeGrade();

            if (!$this->requestModel->action == GradeRequest::ACTION_COMPILE) {
                $this->doGrade();
                //$this->requestModel->graded_time = new CDbExpression("NOW()");
                $this->requestModel->graded_time = date("Y-m-d H:i:s");
            }
        }
        $this->afterGrade();

        $this->requestModel->report = json_encode(array(
            'compile_result' => array(
                'output' => $this->compiler->getCompileOutput(),
                'return' => $this->compiler->getCompileReturnValue()
            ),
            'grade_result' => $this->gradeResult
                ));
        $this->requestModel->status = GradeRequest::STATUS_GRADED;
        //$this->requestModel->report_time = new CDbExpression("NOW()");
        $this->requestModel->report_time = date("Y-m-d H:i:s");
        $this->requestModel->save();
    }

    public final function getGradeResult() {
        return $this->gradeResult;
    }

}

?>
